<?php

class _F_EXTENSION_HTML_ extends _F_EXTENSION_ {
	
	public $prev_callback;
	public $modernizr = '2.5.3';
	public $metas = array(); 

	public $layout = array(
		'header' => 'html.header',
		'layout' => 'html.onecol',
		'navigation' => 'html.navigation',
		'footer' => 'html.footer',
	);
	
	public function __construct() {
		f()->template_path_list[] = dirname(__FILE__).'/templates';
		f()->register_method('a',array($this,'a'));
		f()->register_method('attr',array($this,'attr'));
		f()->register_method('img',array($this,'img'));
		f()->register_method('layout',array($this,'layout'));
		f()->register_method('link',array($this,'link'));
		f()->register_method('meta',array($this,'meta'));
		f()->register_method('http_header',array($this,'http_header'));
		f()->import('style');
		$this->prev_callback = f()->register_method(
			'post_process_callback',array($this,'_f_callback_'));
		f()->import('script');
	}
	
	public function a($address,$html,$attr = null) {
		return '<a href="'.f()->url($address).'"'.$this->attr($attr).'>'.$html.'</a>';
	}

	public function attr($attr) {
		$str = '';
		if (is_array($attr)) {
			foreach ($attr as $name => $value) {
				if (isset($value)) $str .= ' '.$name.'="'.htmlspecialchars($value).'"';
			}
		}
		return $str;
	}

	public function img($address,$attr = null) {
		return '<img src="'.f()->url($address).'"'.$this->attr($attr).' />';
	}

	public function layout($name,$value = null) {
		if (func_num_args() > 1) {
			$this->layout[$name] = $value;
			return f();
		}
		if (is_array($name)) {
			foreach ($name as $key => $value) 
				$this->layout[$key] = $value;
			return f();
		}
		return $this->layout[$name];
	}

	public function link($address,$label,$attr = null) {
		return $this->a($address,htmlspecialchars($label),$attr);
	}

	public function meta($name,$content,$attr = array()) {
		if (isset($content)) $attr = array('content' => $content) + $attr;
		if (isset($name)) $attr = array('name' => $name) + $attr;
		$this->metas[] = $attr;
		return $this;
	}

	public function http_header($name,$content) {
		header("$name: $content");
		return $this->metas[] = array('http-equiv' => $name, 'content' => $content);
		return $this;
	}

	public function _f_callback_() {
		if (isset($this->prev_callback)) call_user_func($this->prev_callback);
		$buffer = '';
		foreach ($this->metas as $attr) {
			$attr =	f()->attr($attr);
			$buffer .= "<meta$attr/>\r\n";
		}
		if (isset($this->modernizr)) $buffer .= '<script src="'.
			f()->url_base.'/extensions/html/scripts/modernizr-'.
			$this->modernizr.".min.js\"></script>\r\n";
		f()->content = preg_replace('/<\/head>/im',"$buffer</head>",f()->content);
	}

	
}

new _F_EXTENSION_HTML_;